// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
const rp = require('request-promise')

cloud.init()

const BASE_URL = 'http://musicapi.xiecheng.live'

// 云函数入口函数
exports.main = async(event, context) => {
  const app = new TcbRouter({
    event
  })

  // 歌单列表
  app.router('playlist', async(ctx, next) => {
    ctx.body = await cloud.database().collection('playlist')
      .skip(event.start)
      .limit(event.count)
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        console.log(res)
        return res
      })
  })

  // 音乐列表
  app.router('musiclist', async(ctx, next) => {
    ctx.body = await rp(`${BASE_URL}/playlist/detail?id=${parseInt(event.playlistId)}`).then(res => {
      return JSON.parse(res).playlist
    })
  })

  // 播放音乐
  app.router('musicUrl', async(ctx, next) => {
    const result = await rp(`${BASE_URL}/song/url?id=${parseInt(event.musiclistId)}`).then(res => {
      return res
    })
    console.log(result)
    ctx.body = {
      code: 0,
      data: result
    }
  })

  // 获取歌词
  app.router('lyric', async (ctx, next) => {
    const result = await rp(`${BASE_URL}/lyric?id=${parseInt(event.musiclistId)}`).then(res => {
      return res
    })
    ctx.body = {
      code: 0,
      data: result
    }
  })

  return app.serve()
}